<template>
    <el-button type="primary" @click="open = true">添加用户</el-button>
    <el-drawer v-model="open" title="添加用户" direction="rtl">
        <el-form ref="ruleFormRef" :model="formItem" :rules="rules" label-width="auto">
            <el-form-item label="真实姓名" prop="name">
                <el-input v-model="formItem.name" clearable />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
                <el-input v-model="formItem.phone" clearable />
            </el-form-item>
            <el-form-item label="登录密码" prop="password">
                <el-input v-model="formItem.password" type="password" clearable />
            </el-form-item>
            <el-form-item label="确认密码" prop="confirmPassword">
                <el-input v-model="formItem.confirmPassword" type="password" clearable />
            </el-form-item>
            <el-form-item label="用户等级">
                <el-select v-model="formItem.gradeId">
                    <el-option :label="item.name" :value="String(item._id)" v-for="item in userGradeData.rows"
                        :key="item._id" />
                </el-select>
            </el-form-item>
            <el-form-item label="用户分组">
                <el-select v-model="formItem.groupId">
                    <el-option :label="item.name" :value="String(item._id)" v-for="item in userGroupData.rows"
                        :key="item._id" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button @click="onAddUser(ruleFormRef)">添加</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
</template>

<script setup lang="ts">
import {  reactive, ref, watch } from 'vue';
import type { FormInstance, FormRules } from 'element-plus'
import type { UserItemType } from '@/api/user';
import { useFindData } from '@/composables/findData';

const open = ref(false);
// Partial<UserItemType>：
// Partial表示基于UserItemType创建出一个新的类型，属性和UserItemType一样，但是全都是可选
const formItem = ref<Partial<UserItemType>>({});
const ruleFormRef = ref<FormInstance>();

const { userGradeData, findUserGradeAsync, userGroupData, findUserGroupAsync } = useFindData();

// 当弹窗打开时，才发送请求获取数据
watch(open, () => {
    if (open.value) {
        findUserGroupAsync();
        findUserGradeAsync()
    }
})

// 表单验证规则
const rules = reactive<FormRules<UserItemType>>({
    name: [
        // 必填（内容不能为空）
        { required: true, message: '用户昵称不能为空', trigger: 'blur' },
        // { min: 3, max: 5, message: 'Length should be 3 to 5', trigger: 'blur' },
    ],
    phone: [
        // 必填（内容不能为空）
        { required: true, message: '手机号不能为空', trigger: 'blur' },
        {
            // validator验证方法
            validator(_, value) {
                const phoneRegExp = /^1[3456789]\d{9}$/
                return phoneRegExp.test(value);
            },
            message: '手机号格式不正确',
            trigger: 'blur'
        },
    ],
    password: [
        // 必填（内容不能为空）
        { required: true, message: '密码不能为空', trigger: 'blur' },
    ],
    confirmPassword: [
        // 验证规则一：必填（内容不能为空）
        { required: true, message: '确认密码不能为空', trigger: 'blur' },
        // 验证规则二：两次密码是否一致
        {
            validator(_, value) {
                // 判断value（确认密码）和password（密码）是否相等
                return value == formItem.value.password;
            },
            message: '两次密码不一致',
            trigger: 'blur'
        },
    ],
})

// 确认添加
async function onAddUser(formEl: FormInstance | undefined) {
    if (!formEl) return;
    await formEl.validate((valid, fields) => {
        if (valid) {
            // 表单中所有的验证规则都通过
            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}

</script>

<style scoped></style>